import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from utils.views import LoginRequiredJsonMixin

from apps.products.models import Product


class CartsView(LoginRequiredJsonMixin, View):
    """购物车"""

    def post(self, request):
        """添加商品到购物车"""
        data = json.loads(request.body.decode())
        product_id = data.get('product_id')
        num = int(data.get('num'))
        try:
            product = Product.objects.get(product_id=product_id)
        except Product.DoesNotExist:
            return JsonResponse({'code': 401, 'errmsg': '没有该商品'})
        user = request.user
        # 如果是登录用户，则将用户想要添加到购物车的商品id添加到redis中
        # 反之，则直接返回错误信息
        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            # 将用户的购物车数据添加到redis的 hash表中
            # 将购物车商品的选中状态添加到set集合中（默认是选中状态）
            redis_cli.hset('cart_%s' % user.user_id, product_id, num)
            redis_cli.sadd('selected_%s' % user.user_id, product_id)
            return JsonResponse({'code': 0, 'errmsg': '添加成功！'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '请先登录！'})

    def get(self, request):
        """获取购物车数据"""
        global product_id
        user = request.user
        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            # 获取该用户的所有购物车商品信息
            products_ids_count = redis_cli.hgetall('cart_%s' % user.user_id)  # {product_id:count,product_id:count,...}
            selected_ids = redis_cli.smembers('selected_%s' % user.user_id)
            carts = {}
            for product_id, count in products_ids_count.items():
                carts[product_id] = {
                    'count': int(count),
                    'selected': product_id in selected_ids  # 判断商品是否被选中，若是则返回 true
                }
            # {product_id:{count:count,selected:true/false}}
            product_ids = carts.keys()  # [1,2,3,...]
            # 范围查询
            products = Product.objects.filter(product_id__in=product_ids)
            product_list = []
            for product in products:
                product_list.append({
                    'id': product.product_id,
                    'name': product.product_name,
                    'price': product.price,
                    'image_url': product.img_url,
                    'selected': carts.get(product_id).get('selected'),
                    'count': carts.get(product_id).get('count'),
                    'amount': product.price * carts.get(product_id).get('count')
                })
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_products': product_list})

    def put(self, request):
        """更新购物车商品信息"""
        data = json.loads(request.body.decode())
        product_id = data.get('product_id')
        count = int(data.get('count'))
        selected = data.get('selected')
        if not all([product_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        try:
            product = Product.objects.get(product_id=product_id)
        except Product.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '商品不存在'})
        user = request.user
        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            redis_cli.hset('cart_%s' % user.user_id, product_id, count)
            if selected:
                redis_cli.sadd('selected_%s' % user.user_id, product_id)
            else:
                redis_cli.srem('selected_%s' % user.user_id, product_id)
            cart_product = {
                'id': product_id,
                'count': count,
                'selected': selected,
                'name': product.product_name,
                'image_url': product.img_url,
                'price': product.price,
                'amount': product.price * count,
            }
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_product': cart_product})
        else:
            return JsonResponse({'code': 400, 'errmsg': '请先登录！'})

    def delete(self,request):
        """将商品移除购物车"""
        data = json.loads(request.body.decode())
        product_id = data.get('product_id')
        try:
            product = Product.objects.get(product_id=product_id)
        except Product.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '商品不存在'})
        user = request.user
        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            redis_cli.hdel('cart_%s' % user.user_id, product_id)
            redis_cli.srem('selected_%s' % user.user_id, product_id)
            return JsonResponse({'code': 0, 'errmsg': '移除成功'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '请先登录！'})


class CartsSelectedAllView(View):
    """购物车全选"""
    def put(self, request):
        data = json.loads(request.body.decode())
        selected = data.get('selected')
        user = request.user
        redis_cli = get_redis_connection('carts')
        cart = redis_cli.hgetall('cart_%s'%user.user_id)
        product_ids = cart.keys()
        if selected:
            # 全选
            redis_cli.sadd('selected_%s' % user.user_id, *product_ids)
        else:
            # 取消全选
            redis_cli.srem('selected_%s' % user.user_id, *product_ids)
        return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})